var makeAfeHostUrl = function(hostname) {
  return 'http://' + autotest_web +
      '/afe/#tab_id=view_host&object_id=' + hostname;
}

var makeTkoHostUrl = function(hostname) {
  return 'http://' + autotest_web +
      '/new_tko/#tab_id=spreadsheet_view&' +
      'row=hostname&column=test_name&' +
      'show_incomplete=true&show_only_latest=false&show_invalid=false&' +
      'condition=hostname+%253D+%27' + hostname + '%27';
}

var makeAfeJobIdUrl = function(job_tag_or_id) {
  var dash = job_tag_or_id.indexOf('-');
  if (dash >= 0) {
    job_tag_or_id = job_tag_or_id.substr(0, dash);
  }
  return 'http://' + autotest_web +
      '/afe/#tab_id=view_job&object_id=' + job_tag_or_id;
}

var makeTkoJobUrl = function(job_tag_or_idx) {
  var dash = job_tag_or_idx.indexOf('-');
  var name = dash >= 0 ? 'job_tag' : 'job_idx';
  return 'http://' + autotest_web +
      '/new_tko/#tab_id=spreadsheet_view&' +
      'row=hostname&column=test_name&' +
      'show_incomplete=true&show_only_latest=false&show_invalid=true&' +
      'condition=' + name + '+%253D+%27' +
      encodeURIComponent(job_tag_or_idx) + '%27';
}

var makeTkoJobTableViewUrl = function(job_tag_or_idx) {
  var dash = job_tag_or_idx.indexOf('-');
  var name = dash >= 0 ? 'job_tag' : 'job_idx';
  return 'http://' + autotest_web +
      '/new_tko/#tab_id=table_view&show_invalid=true&' +
      'condition=' + name + '+%253D+%27' +
      encodeURIComponent(job_tag_or_idx) + '%27';
}

var makeTkoTestUrl = function(test_idx) {
  return 'http://' + autotest_web +
      '/new_tko/#tab_id=table_view&show_invalid=true&' +
      'condition=test_idx+%253D+%27' +
      encodeURIComponent(test_idx) + '%27';
}

var makeAutotestLogUrl = function(job_tag) {
  return 'http://' + autotest_web +
      '/tko/retrieve_logs.cgi?job=/results/' + job_tag;
}

var makeTestUrl = function(job_name) {
  return '/test?' + encodeURIComponent(job_name);
}

var makeHostNotesUrl = function(hostname) {
  return '/hosts/notes?hostname=' + hostname;
}

var makeTriageInfoUrl = function(job_tag) {
  return '/triage?job=' + encodeURIComponent(job_tag);
}

var createTooltipDiv = function(id) {
  var div = document.getElementById(id);
  if (!div) {
    div = document.createElement('div');
    div.id = id;
    div.style.display = 'none';
    document.body.appendChild(div);
  }
  return div;
}

var initTestsTable = function() {
  var tests_table = document.getElementById('tests_table');
  if (tests_table) {
    var as = tests_table.getElementsByTagName('a');
    for (var i = 0; i < as.length; ++i) {
      as[i].href = makeTestUrl(as[i].innerHTML);
    }
  }
}

var getHostnameTooltipInnerHTML = function(hostname) {
  return 'TKO'.link(makeTkoHostUrl(hostname));
}

var showHostnameTooltip = function(e) {
  var me = getActivatedObject(e);
  var div = document.getElementById('hostname_tooltip_div');
  div.innerHTML = getHostnameTooltipInnerHTML(me.innerHTML);
  TagToTip('hostname_tooltip_div');
}

var initHostnameLi = function() {
  var lis = getElementsByClass('hostnames', document.body, 'li');
  if (lis.length) {
    createTooltipDiv('hostname_tooltip_div');
    for (var i = 0; i < lis.length; ++i) {
      var as = lis[i].getElementsByTagName('a');
      for (var j = 0; j < as.length; ++j) {
        as[j].href = makeAfeHostUrl(as[j].innerHTML);
        addEvent(as[j], 'mouseover', showHostnameTooltip);
        addEvent(as[j], 'mouseout', UnTip);
      }
    }
  }
}

var getOverridedNotes = function(notes) {
  return notes;
}

var hostNotesWithEdit = function(notes, hostname) {
  if (!notes) {
    notes = 'None';
  } else if (notes != 'None') {
    notes = '<span class="host_notes">' +
        getOverridedNotes(notes) + '</span>';
  }
  var edit = '';
  if (super_user) {
    edit = ' ' + 'Edit'.link(makeHostNotesUrl(hostname)).sub();
  }
  return notes + edit;
}

var initHostsTable = function() {
  var hosts_table = document.getElementById('hosts_table');
  if (hosts_table) {
    createTooltipDiv('hostname_tooltip_div');
    var trs = hosts_table.getElementsByTagName('tr');
    for (var i = 0; i < trs.length; ++i) {
      var tds = trs[i].getElementsByTagName('td');
      if (tds.length >= 2) {
        var a = firstElementChild(tds[0]);
        if (a) {
          var hostname = a.innerHTML;
          a.href = makeAfeHostUrl(hostname);
          addEvent(a, 'mouseover', showHostnameTooltip);
          addEvent(a, 'mouseout', UnTip);
          var notes_td = tds[tds.length - 1];
          notes_td.innerHTML = hostNotesWithEdit(notes_td.innerHTML, hostname);
        }
      }
    }
  }
}

var showTriageSymptomsTooltip = function(e) {
  var me = getActivatedObject(e);
  var div = nextElementSiblingWithTagName(me, 'div') ||
      firstElementChildWithTagName(me, 'div');
  if (div)
    Tip(div.innerHTML);
}

var initStatsTable = function() {
  var stats_tables = getElementsByClass('stats_table', document.body, 'table');
  for (var i = 0; i < stats_tables.length; ++i) {
    var divs = getElementsByClass('triage_symptoms_div',
                                  stats_tables[i], 'div');
    for (var j = 0; j < divs.length; ++j) {
      var p = previousElementSiblingWithTagName(divs[j], 'a') ||
          parentElement(divs[j]);
      if (p) {
        divs[j].innerHTML = getOverridedNotes(divs[j].innerHTML);
        addEvent(p, 'mouseover', showTriageSymptomsTooltip);
        addEvent(p, 'mouseout', UnTip);
      }
    }
  }
}

var showHostnameNotesTooltip = function(e) {
  var me = getActivatedObject(e);
  var div = document.getElementById('hostname_notes_tooltip_div');
  var hostname = me.innerHTML.split(' ', 1)[0];
  div.innerHTML =
      hostNotesWithEdit(me.dioxide_host_notes, hostname) + '<br>' +
      'AFE'.link(makeAfeHostUrl(hostname)) + ' ' +
      getHostnameTooltipInnerHTML(hostname).replace('<br>', ' ');
  TagToTip('hostname_notes_tooltip_div');
}

var initHssTable = function(table_id) {

  function process_th(th) {
    var c = firstElementChild(th);
    if (c) {
      c.dioxide_host_notes = c.title;
      c.title = null;
      addEvent(c, 'mouseover', showHostnameNotesTooltip);
      addEvent(c, 'mouseout', UnTip);
    }
  }

  var table = document.getElementById(table_id);
  if (table) {
    createTooltipDiv('hostname_notes_tooltip_div');
    var trs = table.getElementsByTagName('tr');
    for (var i = 0; i < trs.length; ++i) {
      var ths = trs[i].getElementsByTagName('th');
      if (ths.length == 1) {
        process_th(ths[0]);
      }
    }
  }
}

var initStatusTable = function() {
  var status_table = document.getElementById('status_table');
  if (status_table) {
    var divs = getElementsByClass('triage_symptoms_div',
                                  status_table, 'div');
    for (var i = 0; i < divs.length; ++i) {
      var a = previousElementSiblingWithTagName(divs[i], 'a');
      if (a) {
        var job_tag = a.title;
        a.title = null;
        a.href = makeTkoJobUrl(job_tag);
        var spans = divs[i].getElementsByTagName('span');
        if (spans.length == 2) {
          if (!spans[0].innerHTML) {
            spans[0].innerHTML = 'None';
          } else if (spans[0].innerHTML != 'None') {
            addClass(spans[0], 'triage_info');
          }
          if (!spans[1].innerHTML) {
            spans[1].innerHTML = 'None';
          } else if (spans[1].innerHTML != 'None') {
            addClass(spans[1], 'symptoms');
          }
          var inner_div = firstElementChildWithTagName(divs[i], 'div');
          inner_div.innerHTML += '<br><span>' +
              (super_user ? 'Triage' : 'Details').link(
                  makeTriageInfoUrl(job_tag)) + ' ' +
              'AFE'.link(makeAfeJobIdUrl(job_tag)) + ' ' +
              'TKO'.link(makeTkoJobTableViewUrl(job_tag)) + ' ' +
              'Logs'.link(makeAutotestLogUrl(job_tag)) + '</span>';
        }
        divs[i].innerHTML = getOverridedNotes(divs[i].innerHTML);
        addEvent(a, 'mouseover', showTriageSymptomsTooltip);
        addEvent(a, 'mouseout', UnTip);
      }
    }
  }
}

var initForms = function() {

  function create_method_closure(o, method) {
    return function() {
      o[method]();
    }
  }

  function create_form_submit_closure(radio, text) {
    return function() {
      if (!radio.checked)
        text.disabled = true;
    }
  }

  var names = ['set_notes', 'set_triage_info'];
  for (var i = 0; i < names.length; ++i) {
    var inputs = document.getElementsByName(names[i]);
    for (var j = 0; j < inputs.length; ++j) {
      if (inputs[j].value == 'true') {
        var text_input = nextElementSiblingWithTagName(inputs[j], 'input');
        var form = inputs[j].form;
        if (text_input && form) {
          if (text_input.disabled && !inputs[j].disabled)
            text_input.disabled = false;
          addEvent(inputs[j], 'focus',
                   create_method_closure(text_input, 'focus'));
          addEvent(text_input, 'focus',
                   create_method_closure(inputs[j], 'click'));
          addEvent(form, 'submit',
                   create_form_submit_closure(inputs[j], text_input));
        }
      }
    }
  }
}

var initJobHostRunTestViewTable = function() {
  var job_host_run_list_tables = getElementsByClass(
      'job_host_run_list_table', document, 'div');
  for (var i = 0; i < job_host_run_list_tables.length; ++i) {
    var as = job_host_run_list_tables[i].getElementsByTagName('a');
    for (var j = 0; j < as.length; ++j) {
      if (as[j].innerHTML.indexOf('-') >= 0)
        as[j].href = makeTkoJobUrl(as[j].innerHTML);
      else
        as[j].href = makeTkoJobTableViewUrl(as[j].innerHTML);
    }
  }

  var test_views_tables = getElementsByClass(
      'test_views_table', document, 'table');
  for (var i = 0; i < test_views_tables.length; ++i) {
    var as = test_views_tables[i].getElementsByTagName('a');
    for (var j = 0; j < as.length; ++j) {
      as[j].href = makeTkoTestUrl(as[j].innerHTML);
    }
  }

  var job_host_runs_tables = getElementsByClass(
      'job_host_runs_table', document, 'table');
  for (var i = 0; i < job_host_runs_tables.length; ++i) {
    var as = job_host_runs_tables[i].getElementsByTagName('a');
    for (var j = 0; j < as.length; ++j) {
      if (as[j].innerHTML.indexOf('-') >= 0)
        as[j].href = makeTkoJobUrl(as[j].innerHTML);
      else
        as[j].href = makeTkoJobTableViewUrl(as[j].innerHTML);
    }
  }
}

var initPage = function() {
  if (!init_page_called) {
    init_page_called = true;

    initTestsTable();
    initHostnameLi();
    initHostsTable();
    initStatsTable();
    var hss_table_ids = [
        'hosts_results_table',
        'hosts_runtime_table',
        'status_table'];
    for (var i = 0; i < hss_table_ids.length; ++i) {
      initHssTable(hss_table_ids[i]);
    }
    initStatusTable();
    initForms();
    initJobHostRunTestViewTable();
  }
}

if (!autotest_web)
  var autotest_web = 'autotest';
if (!super_user)
  var super_user = false;
var init_page_called = false;
addEvent(document, 'DOMContentLoaded', initPage);
addEvent(window, 'load', initPage);
